const nfcService = require('../service/nfc-service');
const app = getApp()
var mfcObj = null
Page({
    data: {
        readCmd: 0x30,
        authCmd: 0x60,
        writeCmd: 0x61,
        readKey: [0x6E, 0x6F, 0x72, 0x64, 0x69, 0x63],
        writeKey: [0x62, 0x10, 0x5e, 0x86, 0x53, 0x4e],
        auth_control: [0x78, 0x77, 0x88, 0x69],
        isBlankCard: false,
        blankAuthKey: [0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
        errColor: 'red',
        writeSucDesc: '写卡成功',
        wFlg: -1,
    },
    onLoad: function (options) {
        let that = this
        const nfc = wx.getNFCAdapter()
        this.nfc = nfc
        let sRfid = options.sRfid
        this.initWriteContent(sRfid)

        function connectCard(mfc) {
            mfc.connect({
                complete(res) {
                    if (res.errno == 0) {
                        console.log("connect suc：", res)
                        that.data.conRetryCount = null
                        that.readTractiveCmd()
                    } else {
                        if(!that.data.conRetryCount) {
                            that.data.conRetryCount = 50
                        }
                        console.error("connect 失败：", res, that.data.conRetryCount)
                        that.data.conRetryCount = that.data.conRetryCount - 1
                        if(that.data.conRetryCount > 0) {
                            connectCard(mfc)
                        }                        
                    }
                }
            })
        }

        function discoverHandler(res) {
            console.log("发现卡，读取到的卡:", res)
            let factoryRfid = that.hexFromBuffer(res.id)
            console.log("获取到factoryRfid：", factoryRfid)
            that.setData({
                orignRfid: factoryRfid
            })

            if (res.techs.includes(nfc.tech.mifareClassic)) {
                //读取rfid
                const mfc = nfc.getMifareClassic()
                mfcObj = mfc
                connectCard(mfc)
                return
            }

        }

        nfc.onDiscovered(discoverHandler)
        nfc.startDiscovery({
            fail(err) {
                console.log('failed to discover:', err)
            }
        })
    },

    onShow() {
        //检查nfc并进行初始等恢复操作
    },

    onHide() {
        // if (this.nfc) {
        //     this.nfc.stopDiscovery()
        // }
    },
    initWriteContent(rfid) {
        this.setData({
            scanRfid: rfid,
            rfid: '',
            errColor: 'red',
            errStat: false,
            errInfo: '',
            equNum: '',
            hosName: '',
            orignRfid: '',
            writeDate: '',
        })
    },
    rfidInput(e) {
        let rfid = e.detail.value
        console.log("input rfid-->", e, rfid)
        this.data.inputRfid = rfid
        if (rfid && rfid.length == 8) {
            this.initWriteContent(rfid)
        }
    },

    scanCode() {
        let that = this
        wx.scanCode({
            success(res) {
                console.log("扫码结果：", res)
                console.log("二维内容:", res.result)
                let sRfid = res.result
                that.setData({
                    scanRfid: sRfid
                })
                that.initWriteContent(sRfid)

            }
        })
    },

    writeRfid() {
        let that = this
        let mfc = mfcObj
        if (!that.data.scanRfid) {
            wx.showToast({
                title: '请扫码或输入rfid',
            })
            return
        }
        mfc.close({
            success(res) {
                console.log("nfc 关闭连接成功:", res)
                mfc.connect({
                    success(res) {
                        console.log("nfc 连接成功:", res, '是否空卡:', that.data.isBlankCard)
                        let authWriteArr = [0x61, 0x04, 0x02, 0xf4, 0x6e, 0x75, 0x62, 0x10, 0x5e, 0x86, 0x53, 0x4e]
                        if (that.data.isBlankCard) {
                            authWriteArr = [0x61, 0x04, 0x02, 0xf4, 0x6e, 0x75, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
                        }
                        nfcService.getEquNumByRfid({
                            "rfid": that.data.scanRfid
                        }, (data) => {
                            let equNum = data.data
                            if (equNum) {

                                let curDate = new Date()
                                let year = curDate.getFullYear().toString().substring(2, 4)
                                let month = curDate.getMonth() + 1
                                let date = curDate.getDate()
                                //长度6位
                                let writeDate = year + (month > 9 ? month : '0' + month) + (date > 9 ? date : '0' + date)
                                //长度8位
                                let equNumHex = that.paddingZeroStrBefore(parseInt(equNum).toString(16), 8)
                                //设备类型2位：01轮椅rfid, 00旧设备rfid，02卡rfid
                                let equType = '01'
                                let writeContent = that.data.scanRfid + '00000000' + writeDate + equNumHex + equType;
                                console.log("要写入的内容:", writeContent)
                                let writeCmd = [0xA0, 0x04]
                                let len = writeContent.length
                                for (let i = 0; i < len; i += 2) {
                                    let item = writeContent.substring(i, i + 2)
                                    writeCmd.push(parseInt('0x' + item))
                                }
                                mfc.transceive({
                                    data: new Uint8Array(authWriteArr).buffer,
                                    complete(res) {
                                        let rfidContent = that.hexFromBuffer(res.data)
                                        console.log('===auth>write res:', res)
                                        console.log('===auth>write:', rfidContent)
                                        let writeCmdArr = writeCmd
                                        let paddingLen = 18 - writeCmdArr.length
                                        for (let i = 0; i < paddingLen; i++) {
                                            writeCmdArr.push(0x0)
                                        }
                                        console.log('===write>t:', writeCmdArr, writeCmdArr.length)
                                        mfc.transceive({
                                            data: new Uint8Array(writeCmdArr).buffer,
                                            complete(res) {                                                
                                                if(res.errno != 0) {
                                                    console.error('写数据res fail:', res, that.data.writeRetryCount)
                                                    if(!that.data.writeRetryCount) {
                                                        that.data.writeRetryCount = 10
                                                    }
                                                    that.data.writeRetryCount = that.data.writeRetryCount - 1
                                                    if(that.data.writeRetryCount > 0) {
                                                        that.writeRfid()
                                                    }else {
                                                       that.setData({
                                                           errColor:"red",
                                                           errInfo: "写卡失败:" + res.errno,
                                                           errStat: true
                                                       })
                                                    }
                                                    return
                                                }
                                                that.data.writeRetryCount = null
                                                console.log('写数据res suc:', res)
                                                let rfidContent = that.hexFromBuffer(res.data)
                                                console.log('=写数据==>rfidContent:', rfidContent)
                                                nfcService.logWriteRfid({
                                                    "factoryRfid": that.data.orignRfid,
                                                    "writeRfid": that.data.scanRfid,
                                                    "equNum": equNum,
                                                    "rfidType": equType
                                                }, (data) => {})

                                                that.setData({
                                                    scanRfid: '',
                                                    errInfo: that.data.writeSucDesc,
                                                    errColor: 'green',
                                                    errStat: true
                                                })
                                                that.data.wFlg = 1
                                                //重新读取
                                                that.readTractiveCmd()
                                            }
                                        })


                                        if (that.data.isBlankCard) {
                                            let authBytes = [0xA0, 0x07]
                                            authBytes = authBytes.concat(that.data.readKey)
                                            authBytes = authBytes.concat(that.data.auth_control)
                                            authBytes = authBytes.concat(that.data.writeKey)
                                            let paddingLen = 18 - authBytes.length
                                            for (let i = 0; i < paddingLen; i++) {
                                                authBytes.push(0x0)
                                            }
                                            mfc.transceive({
                                                data: new Uint8Array(authBytes).buffer,
                                                complete(res) {
                                                    if(res.errno != 0) {
                                                        console.error('写权限res fail:', res, that.data.writeAuthRetryCount)
                                                        if(!that.data.writeAuthRetryCount) {
                                                            that.data.writeAuthRetryCount = 10
                                                        }
                                                        that.data.writeAuthRetryCount = that.data.writeAuthRetryCount - 1
                                                        if(that.data.writeAuthRetryCount > 0) {
                                                            that.writeRfid()
                                                        }else {
                                                           that.setData({
                                                               errColor:"red",
                                                               errInfo: "写权限失败:" + res.errno,
                                                               errStat: true
                                                           })
                                                        }
                                                        return
                                                    }
                                                    that.data.writeAuthRetryCount = null
                                                    console.log('写权限res suc:', res)
                                                    let rfidContent = that.hexFromBuffer(res.data)
                                                    console.log('=写权限==>rfidContent:', rfidContent)
                                                    that.data.isBlankCard = false
                                                    //重新读取
                                                    that.readTractiveCmd()
                                                }
                                            })
                                        }

                                    }
                                })
                            } else {
                                wx.showToast({
                                    title: '设备编号不存在',
                                })
                            }
                        })


                    },
                    fail(err) {
                        console.error("nfc 连接失败:", err)
                    }
                })
            },
            fail(res) {
                console.log("nfc 关闭连接失败:", res)
            }
        })
    },
    sendReadCmd(readBuffer) {
        let that = this
        let mfc = mfcObj
        mfc.transceive({
            data: readBuffer,
            complete(res) {
                console.log('读取CMD的数据res:', res)
                if (res.errno != 0) {
                    if (!that.data.sendReadCmdCount) {
                        that.data.sendReadCmdCount = 10
                    } else {
                        that.data.sendReadCmdCount = that.data.sendReadCmdCount - 1
                    }
                    if (that.data.sendReadCmdCount <= 0) {
                        that.setData({
                            errStat: true,
                            errInfo: '读卡重试失败:' + res.errno
                        })
                        that.data.sendReadCmdCount = null
                        return
                    }
                    console.error('读取的数据res失败:', res, that.data.sendReadCmdCount)
                    that.readTractiveCmd()
                    return
                }
                let rfidContent = that.hexFromBuffer(res.data)
                let equType = rfidContent.substring(30, 32)
                let isNewRfid = equType == '00'
                let writeDate = isNewRfid ? that.hexAssciToStr(rfidContent.substring(16, 28)) : rfidContent.substring(16, 22)
                let rfid = rfidContent.substring(0, 8)
                console.log('===>rfidContent:', rfidContent, rfid, writeDate)
                //长度8位
                let equNum = isNewRfid ? '' : parseInt(rfidContent.substring(22, 30), 16)
                if (equNum == '') {
                    nfcService.getEquNumByRfid({
                        "rfid": rfid
                    }, (data) => {
                        that.setData({
                            rfid: rfid,
                            writeDate: writeDate,
                            equNum: data.data,
                            errStat: false
                        })
                    })
                } else {
                    that.setData({
                        rfid: rfid,
                        writeDate: writeDate,
                        equNum: equNum,
                        errStat: false
                    })
                }

                nfcService.logReadRfid({
                    "factoryRfid": that.data.orignRfid,
                    "readRfid": rfid.toUpperCase(),
                    "equNum": equNum,
                    "rfidType": equType
                }, (data) => {})
                if (that.data.wFlg == 0 && that.data.errInfo == that.data.writeSucDesc) {
                    console.log("刚写卡成功")
                    that.setData({
                        errStat: true
                    })
                } else if (that.data.scanRfid && that.data.scanRfid.toUpperCase() == rfid.toUpperCase()) {
                    that.setData({
                        errStat: true,
                        errInfo: 'RFID已写成功',
                        errColor: 'red'
                    })
                } else {
                    that.setData({
                        errStat: true,
                        errColor: 'red',
                        errInfo: !that.data.scanRfid ? '如需写卡请输入rfid，点击写卡按钮' : '此卡rfid与扫码值不符,如需重写请手动点击写卡'
                    })
                }

            }
        })
    },

    readTractiveCmd() {
        let that = this
        let mfc = mfcObj
        let authReadArr = [0x60, 0x04, 0x02, 0xf4, 0x6e, 0x75, 0x6E, 0x6F, 0x72, 0x64, 0x69, 0x63]
        mfc.close({
            success(res) {
                console.log("nfc 读取前关闭连接成功:", res)
                mfc.connect({
                    success(res) {
                        console.log("nfc 读取连接成功:", res)
                        mfc.transceive({
                            data: new Uint8Array(authReadArr).buffer,
                            complete(res) {
                                that.data.wFlg = that.data.wFlg - 1
                                console.log('读取授权数据res:', res)
                                if (res.errno != 0) {
                                    console.log("读取授权失败为空卡,scanRfid:", that.data.scanRfid)
                                    that.setData({
                                        rfid: '空卡',
                                        errColor: 'red',
                                        errStat: false,
                                        errInfo: '',
                                        equNum: '',
                                        hosName: '',
                                        writeDate: '',
                                    })
                                    that.data.isBlankCard = true
                                    if (that.data.scanRfid) {
                                        that.writeRfid()
                                    }
                                    return
                                }
                                that.data.isBlankCard = false
                                let rfidContent = that.hexFromBuffer(res.data)
                                console.log('===auth>rfidContent:', rfidContent)

                                let readCmdArr = [0x30, 0x04]
                                const readBuffer = new Uint8Array(readCmdArr).buffer;
                                that.sendReadCmd(readBuffer)
                            }
                        })
                    }
                })

            }
        })


    },

    //清空为空卡
    cleanBlankCmd() {
        let that = this
        let mfc = mfcObj
        mfc.close({
            success(res) {
                console.log("nfc 关闭连接成功:", res)
                mfc.connect({
                    success(res) {
                        console.log("nfc 连接成功:", res, '是否空卡:', that.data.isBlankCard)
                        let authWriteArr = [0x61, 0x04, 0x02, 0xf4, 0x6e, 0x75, 0x62, 0x10, 0x5e, 0x86, 0x53, 0x4e]
                        mfc.transceive({
                            data: new Uint8Array(authWriteArr).buffer,
                            complete(res) {
                                let rfidContent = that.hexFromBuffer(res.data)
                                console.log('===auth>write blank res:', res)
                                console.log('===auth>write blank:', rfidContent)

                                let writeCmdArr = [0xA0, 0x04]
                                let paddingLen = 18 - writeCmdArr.length
                                for (let i = 0; i < paddingLen; i++) {
                                    writeCmdArr.push(0x00)
                                }
                                console.log('===writeBlank>t:', writeCmdArr, writeCmdArr.length)
                                mfc.transceive({
                                    data: new Uint8Array(writeCmdArr).buffer,
                                    complete(res) {
                                        console.log('写数据res:', res)
                                        let rfidContent = that.hexFromBuffer(res.data)
                                        console.log('=写数据==>rfidContent:', rfidContent)
                                        //重新读取
                                        that.readTractiveCmd()
                                    }
                                })

                                let authBytes = [0xA0, 0x07]
                                let authBlankKey = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
                                authBytes = authBytes.concat(authBlankKey)
                                authBytes = authBytes.concat(that.data.auth_control)
                                authBytes = authBytes.concat(authBlankKey)
                                let blankPaddingLen = 18 - authBytes.length
                                for (let i = 0; i < blankPaddingLen; i++) {
                                    authBytes.push(0x0)
                                }
                                mfc.transceive({
                                    data: new Uint8Array(authBytes).buffer,
                                    complete(res) {
                                        console.log('写blank权限res:', res)
                                        let rfidContent = that.hexFromBuffer(res.data)
                                        console.log('=写blank权限==>rfidContent:', rfidContent)
                                        that.data.isBlankCard = true
                                        //重新读取
                                        that.readTractiveCmd()
                                    }
                                })

                            }
                        })
                    },
                    fail(err) {
                        console.error("nfc 连接失败:", err)
                    }
                })
            },
            fail(res) {
                console.log("nfc 关闭连接失败:", res)
            }
        })
    },

    buf2hex: function buf2hex(buffer) {
        // buffer is an ArrayBuffer
        return String.fromCharCode.apply(null, new Uint8Array(buffer));
    },
    hexFromBuffer(buffer) {
        var hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function (bit) {
                return ('00' + bit.toString(16)).slice(-2)
            }
        )
        return hexArr.join('');
    },
    hexAssciToStr(hexStr) {
        let len = hexStr.length
        let str = ''
        for (let i = 0; i < len; i += 2) {
            str += String.fromCharCode('0x' + hexStr.substring(i, i + 2))
        }
        return str
    },
    strToHexAssci(str) {
        let len = str.length
        let hexStr = ''
        for (let n = 0, l = len; n < l; n++) {
            hexStr += Number(str.charCodeAt(n)).toString(16);
        }
        return hexStr
    },
    paddingZeroStrBefore(str, len) {
        let strLen = str.length
        if (strLen == len) {
            return str
        }
        let paddingCount = len - strLen
        let paddStr = ''
        for (let i = 0; i < paddingCount; i++) {
            paddStr += '0'
        }
        return paddStr + str
    }

})